import { defineStore} from "pinia";
import {ref} from "vue";
import axios from 'axios';
import {FormState} from "@/components/MyForm.vue";
import {message} from "ant-design-vue";
import dayjs from "dayjs"; // ts 环境会报错，不影响运行
// import * as dayjs from "dayjs";  // ts 环境不报错，开发环境不报错，生产环境报错，影响代码运行
import {SettingItem, useSettingStore} from "@/stores/setting";

export const useClueStore = defineStore("clue", () => {
    const settingStore = useSettingStore();
    const count = ref(0);
    const clueList = ref<any[]>([]);

    const postApi = async (form: FormState) => {
        const setting: SettingItem = settingStore.setting;
        const k = setting.k;
        const url = setting.api_url;
        if (!k) {
            message.error("K 参数为空");
            return false;
        }
        if (!url) {
            message.error("API 链接为空");
            return false;
        }

        const data = new FormData();
        const timeStr = dayjs.isDayjs(form.date) ? form.date.format("YYYY-MM-DD HH:mm:ss") : form.date;

        data.append('phone', form.phone);
        data.append('name', form.name);
        data.append('date', timeStr);
        data.append('remark', form.remark);
        data.append('address', form.address);
        data.append('k', k);
        const file = form.fileList?.[0]?.originFileObj;
        console.log("file",file);
        if (settingStore.setting.need_audio && file) {
            data.append('files', file);
        }
        const config = {
            method: 'post',
            maxBodyLength: Infinity,
            url: url,
            data: data,
        };
        const response = await axios.request(config);
        if (response.data.code === 0) {
            message.success(response.data.msg);
            pushClueToList({
                ...form,
                file: file ? URL.createObjectURL(file) : null,
                date: timeStr,
                response: response.data.msg,
            });
            return true;
        } else {
            message.error(response.data?.msg || "提交错误");
        }
        return false;
    }

    const pushClueToList = (form: any) => {
        clueList.value.unshift(form)
    }

    return {
        count,
        clueList,
        postApi,
    };
});

